#!/usr/bin/env python3.9
# I don't pretend this is anywhere near to usable.. -cjb

# write to memory       :xxyyHHHHHHHH... (x+y positions, then hex values)
# clear screen          Z
# tx screen             T
# (set fg/bg colour      Sffffbbbb (hex values for frequencies))

import time,serial

screenx,screeny = 32,16

screen="""\
%7D____________%c________________%6D
________________________________
_%t_____________________________
_%d_____________________________
________________________________
_This is Arduino Uno speaking.__
_I'm just pottering along at____
_16 MHz, generating audio tones_
_that apparently conveys some___
_information when demodulated___
_and presented in a 2D format.._
________________________________
_If you like source code, you___
_can download it from___________
_https://notabug.com/vk2cjb/____
%6E______________________________%70
"""\
.replace('\n','')

callsign = "vk2cjb"
erasechar = '_'
hexdigits = "0123456789ABCDEF"
notouch = [False]*len(screen)*2
screen = screen.replace(erasechar,' ')
timestr = time.strftime("%I:%M %p").lstrip("0").lower()
datestr = time.strftime("%A %d %B %Y")

def ascii2petscii(c):
    c = ord(c)
    if c >= 96 and c <= 127: return chr(c-96)
    return chr(c)

i = 0
while i < len(screen):
    if screen[i] == "%":
        if screen[i+1] == "t":
            screen = screen[:i] + timestr + screen[i+len(timestr):]
        if screen[i+1] == "d":
            screen = screen[:i] + datestr + screen[i+len(datestr):]
        if screen[i+1] == "c":
            screen = screen[:i] + callsign + screen[i+len(callsign):]
        if screen[i+1] in hexdigits and screen[i+2] in hexdigits:
            h = int(screen[i+1:i+3],16)
            screen = screen[:i] + chr(h) + screen[i+3:]
            notouch[i] = True
    if notouch[i] == False:
        screen = screen[:i] + ascii2petscii(screen[i])+ screen[i+1:]
    i += 1

if len(screen) != screenx*screeny: print ("?")

out,p = "Z",0

while len(screen):
    o = ""
    while len(screen):
        xp,yp = p % screenx, p // screenx
        c = "{:02X}".format(ord(screen[0]))
        screen = screen[1:]
        p += 1
        if c == "20":   # don't break if it's only one space character
            if len(o) > 0 and len(screen) > 2 and screen[0] != " ": pass
            else: break
        if o == "": o = ":" + "{:02X}{:02X}".format(yp,xp)
        o += c

    out += o

out = bytes(out+"TZ\n","UTF-8")

ser = serial.Serial("/dev/ttyACM0", 9600)
ser.readline()                  # waits for "START"
ser.write(out)
print (out)
time.sleep(5)
ser.readline()                  # waits for "END"
ser.close()
